package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import view.EditMeetingView;

import view.ViewHelpers;
import model.AppModel;
import model.Email;
import model.EmailBuilder;
import model.Meeting;
import model.ModelException;

/**
 * This class controls the Edit Meeting View
 * 
 * This controller has a reference to the main model, and the current view it is working on.
 * It assigns handlers to events for the cancel and  edit and specifies the actions
 * to invoke upon triggering these events. 
 * 
 * 
 * Controller assigns and handles events of sending and saving an edited meeting
 * @author buthainahaldosary
 * @since May 31, 2013
 *
 * @version $Revision: 1.0 $
 */

public class EditMeetingController
{
	/**
	 * Application model, view and main contrlller
	 */
	private AppModel model;
	
	/**
	 * The view to work on
	 */
	private EditMeetingView view;
	
	/**
	 * The current meeting to work on.
	 */
	private Meeting meeting;
	/**
	 * Constructor
	 * @param model application model to work on
	 * @param meeting Meeting
	 */
	public EditMeetingController(AppModel model,Meeting meeting) {
		this.model = model; 
		this.meeting=meeting;
		setupView();
		

		//setup edit meeting view with current selected meeting values
		
		assignHandlersToEvents();
		view.showDialog();
	}

	/**
	 * This method sets up the edit meeting view with the selected meeting's fields
	 */
	private void setupView() {
		
		view = new EditMeetingView();
		
		view.getAttendees().setText(meeting.getAttendees());
		view.getDescription().setText(meeting.getDescription());
		view.getLocation().setText(meeting.getLocation());
		view.setStartDate(meeting.getStart());
		view.setEndDate(meeting.getEnd());
		view.getTopic().setText(meeting.getTopic());
		
		
	}

	/**
	 * Method to register and assign handlers to events
	 */
	private void assignHandlersToEvents() {
		//edit

		view.getCommitBtn().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				actionCommitMeeting();
			}
		});
		
		/**
		 * Cancel
		 */
		view.getCancelBtn().addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				actionCancel();
			}
		});

		//save changes
		view.getSaveBtn().addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				actionSave();
			}
		});
		
	}

	protected void actionSave() {
	//save the meeting locally
		
		// Sanitize user input
		
				String newLocation = view.getLocationText().toLowerCase().trim();
				//handle string inputs here
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MMMMM.dd hh:mm aaa");
				String newStart = view.getStartDateText().toLowerCase().trim();
				String newEnd=view.getEndDateText().toLowerCase().trim();
				String topic=view.getTopicText();
				Date parsedStartDate=null;
				Date parsedEndDate=null;
				Timestamp startDate = null;
				Timestamp endDate=null;
				
				
				try {
					parsedStartDate = sdf.parse(newStart);
					parsedEndDate = sdf.parse(newEnd);
					 startDate=new Timestamp(parsedStartDate.getTime());
					 endDate=new Timestamp(parsedEndDate.getTime());
				} catch (ParseException e1) {
					
					ViewHelpers.alertError("Please make sure you entered valid inputs for the dates");
					return;
				}
				
				
				String newAttendees=view.getAttendeesText().toLowerCase().trim();
				String newDescription=view.getDescriptionText().toLowerCase().trim();
						
				// validate input
				if (!areValidInputs( newLocation,newStart,newEnd,newAttendees,newDescription)){
					return;
				}
				
				meeting.setAttendees(newAttendees);
				meeting.setDescription(newDescription);
				meeting.setEnd(endDate);
				meeting.setStart(startDate);
				meeting.setLocation(newLocation);
				meeting.setOwner("");
				meeting.setRevisionId(0);
				
				
				try {
					
					//save the meeting locally
					meeting.save();

					ViewHelpers.disposeParentDialog(view.getPanel());
					//}
				}catch (ModelException e) {
					ViewHelpers.alertError("Problem editing meeting.");
					return;
				}
		
	}

	/**
	 * Method that is triggered when the cancel button is clicked.
	 */
	protected void actionCancel() {
		ViewHelpers.disposeParentDialog(view.getPanel());
		
	}

	/**
	 * Method that is triggered when the edit button is clicked, topic can not be edited
	 */
	protected void actionCommitMeeting() {
		// Sanitize user input
		
		String newLocation = view.getLocationText().toLowerCase().trim();
		//handle string inputs here
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MMMMM.dd hh:mm aaa");
		String newStart = view.getStartDateText().toLowerCase().trim();
		String newEnd=view.getEndDateText().toLowerCase().trim();
		String topic=view.getTopicText();
		Date parsedStartDate=null;
		Date parsedEndDate=null;
		Timestamp startDate = null;
		Timestamp endDate=null;
		
		
		try {
			parsedStartDate = sdf.parse(newStart);
			parsedEndDate = sdf.parse(newEnd);
			 startDate=new Timestamp(parsedStartDate.getTime());
			 endDate=new Timestamp(parsedEndDate.getTime());
		} catch (ParseException e1) {
			
			ViewHelpers.alertError("Please make sure you entered valid inputs for the dates");
			return;
		}
		
		
		String newAttendees=view.getAttendeesText().toLowerCase().trim();
		String newDescription=view.getDescriptionText().toLowerCase().trim();
				
		// validate input
		if (!areValidInputs( newLocation,newStart,newEnd,newAttendees,newDescription)){
			return;
		}
		
		meeting.setAttendees(newAttendees);
		meeting.setDescription(newDescription);
		meeting.setEnd(endDate);
		meeting.setStart(startDate);
		meeting.setLocation(newLocation);
		
		
		try {
			
			
			meeting.save();
			//sent emails to reciepients
			//String recipientList=meeting.getAttendees();
			// extract each recipient
			//List<String> recipients = Arrays.asList(recipientList.split(","));
			//create email for each recipient
			String body="";
			java.util.Date date= new java.util.Date();
			 Timestamp currentTime = new Timestamp(date.getTime());
			//for (String recipient : recipients)
			//{
				//recipient=recipient.trim();
				body="Hello ${to}"+"\n A meeting was created (or updated) by "+model.getUser().getName()+" which includes you. Here are the details: \n"+
						"~~~\n"+
						"Hash: "+
			"Start time: "+meeting.getStart().toGMTString()+ "\n "+
						"End time: "+ meeting.getEnd().toGMTString()+ "\n"+
			"Topic: " +meeting.getTopic()+"\n Description: "+ meeting.getDescription()+" \n Other attendees: "+ meeting.getAttendees()+"\n Thank you.";
			//int folderId= model.getUser().getFolder("Outbox").getId();			
			//Email emailToSend =  new EmailBuilder().setFrom(model.getUser().getName()).setTo(meeting.getAttendees()).setSubject(topic).setRead(false).setBody(body).setFolderId(folderId).build();
			//emailToSend.save();
			//model.getUser().getFolder("Outbox").getEmails().add(emailToSend);
				
			//Send email to server
				
			//Result of meeting creation from the server
			//Meeting createdMeeting=
			//createdMeeting.save();
				
			ViewHelpers.disposeParentDialog(view.getPanel());
			//}
		}catch (ModelException e) {
			ViewHelpers.alertError("Problem editing meeting.");
			return;
		}		
	}

	/**
	 * This method validated the meeting input for fields by checking if they are empty or not
	
	
	
	
	
	
	
	 * @param location String
	 * @param start String
	 * @param end String
	 * @param attendees String
	 * @param description String
	 * @return boolean value indicating that the inputs are valid or not. */
	private Boolean areValidInputs( String location,String start, String end, String attendees, String description){
		
		// Empty strings
		if (location.isEmpty()|| start.isEmpty() || end.isEmpty()||attendees.isEmpty()||description.isEmpty()){
			ViewHelpers.alertError("Please make sure all fields are not empty");
			return false;
		}
	
		return true;
				
	}
	
	/**
	 * This method sets the meeting's fields to empty
	 */
	private void refreshView() {
		
		view.getAttendees().setText("");
		view.getDescription().setText("");
		view.getEndDate().setText("");
		view.getStartDate().setText("");
		view.getLocation().setText("");
		view.getTopic().setText("");
		
	}

}
